package com.example.controller;

import com.example.common.Result;
import com.example.mapper.OrderMapper;
import com.example.pojo.Order;
import com.example.service.Impl.OrderService;
import com.example.util.JwtUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/orders")
@Slf4j
public class OrderController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private OrderMapper orderMapper;
    @Resource
    private OrderService orderService;

    @PostMapping("/add")
    public Result add(@RequestBody Order order) {
        int res = orderService.insert(order);
        if (res == 1)
        return Result.success("200","订单创建成功");
        else{
            return Result.error("400","订单创建失败");
        }
    }

    @PutMapping("/cancel")
    public Result cancelOrder(@RequestParam Integer orderId) {
        orderService.cancelOrder(orderId);
        return Result.success("200","订单已取消");
    }

    @GetMapping("/selectAll")
    public Result getOrders(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "3") Integer pageSize,
            @RequestHeader("Authorization") String token,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String roomName) {
        // 从token获取用户信息
        Map<String, Object> claims = JwtUtil.parseToken(token);
        String role = (String) claims.get("role");  // 例如："owner" 或 "user"
        Integer userId = (Integer) claims.get("id");

        return Result.success(orderService.getOrders( userId,role, page, pageSize,status,roomName));
    }

    //支付接口
    @PutMapping("/pay")
    public Result payOrder(@RequestParam Integer orderId) {
        orderService.pay(orderId);
        //订单支付成功
        log.info("订单支付成功");
        return Result.success("200","订单已支付");
    }

    //房东确认订单
    @PutMapping("/confirm")
    public Result confirmOrder(@RequestParam Integer orderId) {
        orderService.confirmOrder(orderId);
        return Result.success("200","订单已确认");
    }

    //用户确认入住
    @PutMapping("/checkIn")
    public Result checkIn(@RequestParam Integer orderId) {
        orderService.checkIn(orderId);
        return Result.success("200","入住成功");
    }

}
